package com.platform.modules.alg.alglib.poj1182;

public class Poj1182 {
    public String output = "";

    private final int N = 50010;
    int n;
    int fa[] = new int[N];
    int d[] = new int[N];

    int Find(int x) {
        int fx = fa[x];
        if (x != fa[x]) {
            fa[x] = Find(fa[x]);
            d[x] = (d[x] + d[fx]) % 3;
        }
        return fa[x];
    }

    void Init() {
        for (int i = 1; i <= n; i++) {
            fa[i] = i;
            d[i] = 0;
        }
    }

    public String cal(String input) {
        String[] line = input.split("\n");
        int k, c, x, y, total = 0, a, b;
        String[] words = line[0].split(" ");
        n = Integer.parseInt(words[0]);
        k = Integer.parseInt(words[1]);
        Init();
        for (int i = 0; i < k; i++) {
            String[] word = line[i + 1].split(" ");
            c = Integer.parseInt(word[0]);
            x = Integer.parseInt(word[1]);
            y = Integer.parseInt(word[2]);

            if (x > n || y > n || (c == 2 && x == y))
                total++;
            else {
                a = Find(x);
                b = Find(y);
                if (a == b) {
                    if ((d[x] - d[y] + 3) % 3 != c - 1)
                        total++;
                } else {
                    fa[a] = b;
                    d[a] = (d[y] - d[x] + 3 + c - 1) % 3;
                }
            }
        }

        output = "" + total;
        return output;
    }
}
